package admin

import (
	"go-weiqi-system/config"
	"go-weiqi-system/internal/models"
	"go-weiqi-system/internal/utils"

	"github.com/gin-gonic/gin"
)

type UserController struct{}

// Index 用户列表
func (ctrl *UserController) Index(c *gin.Context) {
	var param models.PageParam
	if err := c.ShouldBindQuery(&param); err != nil {
		param.Page = 1
		param.PageSize = 10
	}

	keyword := c.Query("keyword")
	status := c.Query("status")

	var users []models.User
	var total int64

	db := config.DB.Model(&models.User{})

	if keyword != "" {
		db = db.Where("nickname LIKE ? OR phone LIKE ?", "%"+keyword+"%", "%"+keyword+"%")
	}
	if status != "" {
		db = db.Where("status = ?", status)
	}

	db.Count(&total)
	db.Order("id desc").
		Offset(param.GetOffset()).
		Limit(param.GetPageSize()).
		Find(&users)

	utils.Success(c, models.PageResponse{
		List:     users,
		Total:    total,
		Page:     param.GetPage(),
		PageSize: param.GetPageSize(),
	})
}

// Detail 用户详情
func (ctrl *UserController) Detail(c *gin.Context) {
	id := c.Query("id")
	if id == "" {
		utils.Error(c, "参数错误")
		return
	}

	var user models.User
	if err := config.DB.First(&user, id).Error; err != nil {
		utils.Error(c, "用户不存在")
		return
	}

	utils.Success(c, user)
}

// UpdateStatus 更新用户状态
func (ctrl *UserController) UpdateStatus(c *gin.Context) {
	var req struct {
		ID     uint `json:"id" binding:"required"`
		Status int  `json:"status" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		utils.Error(c, "参数错误")
		return
	}

	if err := config.DB.Model(&models.User{}).Where("id = ?", req.ID).Update("status", req.Status).Error; err != nil {
		utils.Error(c, "更新失败")
		return
	}

	utils.Success(c, nil, "更新成功")
}

// UpdateScore 更新用户积分
func (ctrl *UserController) UpdateScore(c *gin.Context) {
	var req struct {
		ID                uint    `json:"id" binding:"required"`
		LevelScore        float64 `json:"level_score"`
		ContributionScore float64 `json:"contribution_score"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		utils.Error(c, "参数错误")
		return
	}

	updates := map[string]interface{}{}
	if req.LevelScore >= 0 {
		updates["level_score"] = req.LevelScore
	}
	if req.ContributionScore >= 0 {
		updates["contribution_score"] = req.ContributionScore
	}

	if err := config.DB.Model(&models.User{}).Where("id = ?", req.ID).Updates(updates).Error; err != nil {
		utils.Error(c, "更新失败")
		return
	}

	utils.Success(c, nil, "更新成功")
}

// Statistics 用户统计
func (ctrl *UserController) Statistics(c *gin.Context) {
	var totalUsers int64
	var activeUsers int64

	config.DB.Model(&models.User{}).Count(&totalUsers)
	config.DB.Model(&models.User{}).Where("status = ?", 1).Count(&activeUsers)

	utils.Success(c, gin.H{
		"total_users":  totalUsers,
		"active_users": activeUsers,
	})
}
